package org.example.netty.zdyxieyi;

import com.alibaba.fastjson2.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public class MessageCodec extends ByteToMessageCodec<Message> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {
//        log.info("发送消息了…………{}",message );
        byteBuf.writeInt(11);
        byteBuf.writeByte(1);
        byteBuf.writeByte(1);
        byteBuf.writeInt(message.getMessageType());
        byteBuf.writeInt(message.getSequenceId());

        byte[] msgBytes = new byte[0];
            /*ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bout);
            out.writeObject(message);
            msgBytes = bout.toByteArray();*/
        String jsonString = JSONObject.toJSONString(message);
        msgBytes = jsonString.getBytes();


        byteBuf.writeInt(msgBytes.length);
        byteBuf.writeBytes(msgBytes);
//        log.info("发送消息了{}",message );

    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int magic = byteBuf.readInt();
        byte version = byteBuf.readByte();
        byte serialNumber = byteBuf.readByte();
        int messageType = byteBuf.readInt();
        int sequenceId = byteBuf.readInt();
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes,0,length);
        /*ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(bin);*/
//        Message message = (Message) in.readObject();
        String stringObject = new String(bytes);
        Message message = JSONObject.parseObject(stringObject, Message.class);
        list.add(message);

//        log.info("接收到的消息为：{}", message);

    }
}
